<template>
  <el-dialog
    :model-value="visible"
    @update:model-value="$emit('update:visible', $event)"
    title="编辑订单"
    width="600px"
    :before-close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="100px"
    >
      <el-form-item label="订单号" prop="orderId">
        <el-input v-model="form.orderId" disabled />
      </el-form-item>
      
      <el-form-item label="订单状态" prop="orderStatus">
        <el-select v-model="form.orderStatus" placeholder="请选择订单状态">
          <el-option label="待支付" value="待支付" />
          <el-option label="已支付" value="已支付" />
          <el-option label="已完成" value="已完成" />
          <el-option label="已取消" value="已取消" />
        </el-select>
      </el-form-item>

      <el-form-item label="拍摄时间" prop="shootingTime">
        <el-date-picker
          v-model="form.shootingTime"
          type="datetime"
          placeholder="选择拍摄时间"
          format="YYYY-MM-DD HH:mm:ss"
          value-format="YYYY-MM-DD HH:mm:ss"
        />
      </el-form-item>

      <el-form-item label="订单金额" prop="orderAmount">
        <el-input-number
          v-model="form.orderAmount"
          :precision="2"
          :step="0.01"
          :min="0"
        />
      </el-form-item>

      <el-form-item label="支付方式" prop="paymentMethod">
        <el-select v-model="form.paymentMethod" placeholder="请选择支付方式">
          <el-option label="支付宝" value="alipay" />
          <el-option label="微信支付" value="wechat" />
        </el-select>
      </el-form-item>

      <el-form-item label="收货人" prop="recipientName">
        <el-input v-model="form.recipientName" />
      </el-form-item>

      <el-form-item label="联系电话" prop="phoneNumber">
        <el-input v-model="form.phoneNumber" />
      </el-form-item>

      <el-form-item label="所在地区" prop="region">
        <el-cascader
          v-model="form.region"
          :options="regionOptions"
          :props="cascaderProps"
          placeholder="请选择省市区"
          clearable
        />
      </el-form-item>

      <el-form-item label="详细地址" prop="streetAddress">
        <el-input
          v-model="form.streetAddress"
          type="textarea"
          :rows="3"
          placeholder="请输入详细地址"
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
          确定
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { updateOrderAll } from '@/apis/admin/order'
import { regionData, codeToText } from 'element-china-area-data'

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  orderData: {
    type: Object,
    default: () => ({})
  }
})

const emit = defineEmits(['update:visible', 'success'])

const formRef = ref(null)
const submitLoading = ref(false)

const form = reactive({
  orderId: '',
  orderStatus: '',
  shootingTime: '',
  orderAmount: 0,
  paymentMethod: '',
  id:'',
  recipientName: '',
  phoneNumber: '',
  region: [],
  streetAddress: ''
})

// 省市区选择器配置
const regionOptions = regionData
const cascaderProps = {
  value: 'value',
  label: 'label',
  children: 'children'
}

const rules = {
  orderStatus: [
    { required: true, message: '请选择订单状态', trigger: 'change' }
  ],
  shootingTime: [
    { required: true, message: '请选择拍摄时间', trigger: 'change' }
  ],
  orderAmount: [
    { required: true, message: '请输入订单金额', trigger: 'blur' }
  ],
  paymentMethod: [
    { required: true, message: '请选择支付方式', trigger: 'change' }
  ],
  recipientName: [
    { required: true, message: '请输入收货人姓名', trigger: 'blur' }
  ],
  phoneNumber: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  region: [
    { required: true, message: '请选择所在地区', trigger: 'change' }
  ],
  streetAddress: [
    { required: true, message: '请输入详细地址', trigger: 'blur' }
  ]
}

// 根据地址信息找到对应的地区编码
const findRegionCode = (province, city, district) => {
  const provinceCode = Object.keys(codeToText).find(key => codeToText[key] === province)
  const cityCode = Object.keys(codeToText).find(key => codeToText[key] === city)
  const districtCode = Object.keys(codeToText).find(key => codeToText[key] === district)
  return [provinceCode, cityCode, districtCode].filter(Boolean)
}

// 监听订单数据变化，填充表单
watch(() => props.orderData, (newData) => {
  if (newData && Object.keys(newData).length > 0) {
    const shippingAddress = newData.shippingAddress || {}
    Object.assign(form, {
      orderId: newData.orderId,
      orderStatus: newData.orderStatus,
      shootingTime: newData.shootingTime,
      orderAmount: newData.orderAmount,
      paymentMethod: newData.paymentMethod,
      id:shippingAddress.id,
      recipientName: shippingAddress.recipientName || '',
      phoneNumber: shippingAddress.phoneNumber || '',
      region: findRegionCode(shippingAddress.province, shippingAddress.city, shippingAddress.district),
      streetAddress: shippingAddress.streetAddress || ''
    })
  }
}, { immediate: true })

// 关闭弹窗
const handleClose = () => {
  emit('update:visible', false)
  formRef.value?.resetFields()
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    submitLoading.value = true
    
    // 根据选择的地区编码获取地区名称
    const [provinceCode, cityCode, districtCode] = form.region
    const province = codeToText[provinceCode] || ''
    const city = codeToText[cityCode] || ''
    const district = codeToText[districtCode] || ''
    
    // 构建更新订单的数据结构
    const updateData = {
      orderId: form.orderId,
      orderStatus: form.orderStatus,
      shootingTime: form.shootingTime,
      orderAmount: form.orderAmount,
      paymentMethod: form.paymentMethod,
      // 构建收货地址信息
      shippingAddress: {
        id:form.id,
        recipientName: form.recipientName,
        phoneNumber: form.phoneNumber,
        province: province,
        city: city,
        district: district,
        streetAddress: form.streetAddress
      }
    }
    
    // 调用更新订单的API
    const res = await updateOrderAll(updateData)
    
    if (res.code === '0') {
      ElMessage.success('订单更新成功')
      emit('success')
      handleClose()
    } else {
      ElMessage.error(res.msg || '订单更新失败')
    }
  } catch (error) {
    console.error('订单更新失败:', error)
    ElMessage.error('订单更新失败')
  } finally {
    submitLoading.value = false
  }
}
</script>

<style lang="less" scoped>
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style> 